// pages/order/index.js
import loginFn from '../../utils/login.js'
import urls from '../../utils/urls.js'
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		paynow: false, //正在支付
		gold: 0, //使用多少金币兑换
		score: 0, //使用多少积分兑换
		user_gold: 0, //用户当前金币
		user_integral: 0, //用户当前积分
		number: 1, //商品数量
		orderInfo: {}, //订单数据
		list: [], //课程详情
		totalAmount: 0, //买家需要支付
		promotion: false, //是否有优惠券
		orderId: '',
		promotionAmount: 0, //优惠券金额

		canUseGold: 0, //能抵扣的金币
		canUseScore: 0, //能抵扣的积分
		useGold: false, //是否使用金币抵扣
		useScore: false, //是否使用积分抵扣
		active_id: '',
		active_type: ''
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		console.log('options', options)
		this.setData({
			courseId: options.courseId ? options.courseId : '',
			orderId: options.orderId ? options.orderId : '',
			active_id: options.active_id ? options.active_id : '',
			active_type: options.active_type ? options.active_type : '',
		})

		//课程详情
		this.getclassInfo(options.courseId)

		if (options.courseId && !options.orderId) {
			//新订单
			this.getOrder();
		};

		//支付未支付订单
		if (options.orderId) {
			//获取订单详情
			this.getDetail(options.orderId)
		};


	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	},
	//计算价格
	calculate() {
		//商品总价
		let goodsAmount = this.data.number * this.data.orderInfo.unitPrice;

		//抵扣的积分和金币价格
		let deductibleAmount = this.data.gold + this.data.score/100;

		//优惠券金额
		let promotionAmount = this.data.promotionAmount;


		this.setData({
			totalAmount: Math.floor((goodsAmount - deductibleAmount - promotionAmount)*100)/100,

		});

	},
	//数量加1
	prevNum() { 
		if(this.data.orderId){
			return false;
		}

		var number = parseInt(this.data.number) + 1;
		this.setData({
			number: number,
		});

		this.calculate();
	},
	nextNum() { //数量减1
		if(this.data.orderId){
			return false;
		}
		var number = this.data.number;
		if (this.data.number <= 1) {
			number = 1
		} else {
			number = this.data.number - 1
		}

		this.setData({
			number: number,
		});

		this.calculate();
	},

	//课程详情
	getclassInfo: function(courseId) { 
		var that = this;
		var loginInfo = loginFn()
		loginInfo.courseId = courseId
		wx.request({
			url: urls.courseInfo,
			data: loginInfo,
			success: function(res) {
				console.log(res)
				if (res.data.code == '0') {
					var list = []
					list.push(res.data.data)
					that.setData({
						list: list
					})
				};
			}
		})

	},
	//订单详情
	getOrder: function() { 
		var that = this;
		var loginInfo = loginFn();
		loginInfo.courseId = this.data.courseId;
		loginInfo.active_id = this.data.active_id;
		loginInfo.active_type = this.data.active_type;
		
		wx.request({
			url: urls.orderadd,
			data: loginInfo,
			success: function(res) {
				if (res.data.code == '0') {
					let data = res.data.data;
					//总金额
					var shouldpay = parseFloat(data.buyerShouldPay)
					that.setData({
						orderInfo: res.data.data,
						totalAmount: Math.floor(shouldpay * 100) / 100,
						user_gold: data.leftGold,
						user_integral: data.leftScore,
						canUseGold: data.leftGold > shouldpay ? shouldpay : data.leftGold,
						canUseScore: data.leftScore > shouldpay ? shouldpay : data.leftScore,
					})
					//推荐优惠券
					that.getpromotion(shouldpay)
				} else {
					wx.showModal({
						title: '提示',
						content: res.data.info,
						showCancel: false,
						success: () => {
							wx.redirectTo({
								url: '/pages/myorder/index'
							})
						}
					});
				}
			}
		})
	},
	//使用金币
	usegold: function() { 
		if(this.data.useGold) {
			var canUseGold = 0;
		} else {
			let score = this.data.score/100;
			let gold = this.data.orderInfo.buyerShouldPay - this.data.promotionAmount - score;
			if(gold > this.data.user_gold) {
				var canUseGold = this.data.user_gold;
			} else {
				var canUseGold = gold;
			}
		}
		

			console.log(canUseGold);
		this.setData({
			gold: parseInt(canUseGold),
			useGold: !this.data.useGold
		});
		this.changeCanUseScore();
		this.calculate();
	},

	changeCanUseGold(){
		var user_gold = this.data.user_gold;
		var allAmount = this.data.orderInfo.buyerShouldPay;
		var promotionAmount = this.data.promotionAmount;
		var score = this.data.score/100;

		var amount = allAmount-promotionAmount-score;
		console.log(amount);
		var canUseGold = parseInt(user_gold > amount ? amount : user_gold);
		console.log(canUseGold)
		var gold = this.data.useGold ? canUseGold : 0;
		this.setData({
			canUseGold: canUseGold,
			gold: gold
		});
	},

	changeCanUseScore(){
		var user_integral = this.data.user_integral;
		var allAmount = this.data.orderInfo.buyerShouldPay;
		var promotionAmount = this.data.promotionAmount;
		var gold = this.data.gold;

		var amount = allAmount-promotionAmount-gold;
		var canUseScore = parseInt(user_integral > amount ? amount : user_integral);
		var score = this.data.useScore ? canUseScore : 0;
		this.setData({
			canUseScore: parseInt(canUseScore),
			score: score
		});
	},
	//使用积分
	useintegral: function() {
		if(this.data.useScore) {
			var canUseScore = 0;
		} else {
			let gold = this.data.gold;

			let score = this.data.orderInfo.buyerShouldPay - this.data.promotionAmount - gold;
			if(score > this.data.user_integral) {
				var canUseScore = this.data.user_integral;
			} else {
				var canUseScore = score;
			}
		}
		
			console.log(canUseScore);

		this.setData({
			score: canUseScore,
			useScore: !this.data.useScore,
		});

		this.changeCanUseGold();
		this.calculate();
	},
	payFn: function() { //支付
		var that = this;
		

		if (!this.data.paynow) {
			wx.showLoading({
				title: '提交中',
				mask: true,
			})

			this.setData({
				paynow: true
			})

			var loginInfo = loginFn();
			loginInfo.orderId = this.data.orderInfo.orderId;
			loginInfo.goodsCount = this.data.number;
			loginInfo.gold = this.data.gold;
			loginInfo.score = this.data.score;
			if (this.data.promotion) {
				loginInfo.promotionId = this.data.promotion.promotionId;
			};
			// if (this.data.totalAmount >= 0) {
			// 	loginInfo.totalAmount = this.data.totalAmount;
			// } else {
			// 	loginInfo.totalAmount = 0;
			// }

			wx.request({
				url: urls.ordersign,
				data: loginInfo,
				success: function(res) {
					wx.hideLoading();
					if (res.data.code == '0') {
						var data = res.data.data;
						wx.requestPayment({
							'timeStamp': data.timeStamp,
							'nonceStr': data.nonceStr,
							'package': data.package,
							'signType': data.signType,
							'paySign': data.paySign,
							'signType': 'MD5',
							success(res) {
								wx.redirectTo({
									url: '/pages/ordersuccess/index?active_type='+that.data.active_type+'&courseId='+that.data.courseId,
								})
							},
							fail(res) {
								that.setData({
									paynow: false
								})
							}
						})
					} else if(res.data.code == 88) {
						wx.redirectTo({
							url: '/pages/ordersuccess/index',
						})
					}

				}
			})

		};

	},
	//推荐优惠券
	getpromotion: function(price) { 
		var that = this;
		var loginInfo = loginFn();
		loginInfo.price = price;
		wx.request({
			url: urls.recommend,
			data: loginInfo,
			success: function(res) {
				if (res.data.code == '0') {
					if (res.data.data) {
						var promotionAmount= parseFloat(res.data.data.discountPrice);
						var totalAmount = that.data.orderInfo.buyerShouldPay-promotionAmount;
						var user_gold = that.data.user_gold;
						var user_integral = that.data.user_integral;

						var canUseGold = user_gold > totalAmount ? totalAmount : user_gold;
						var canUseScore = user_integral > totalAmount ? totalAmount : user_integral;

						that.setData({
							promotionAmount: promotionAmount,
							promotion: res.data.data,
							canUseGold: canUseGold,
							canUseScore: canUseScore,
							useGold: false,
							useScore: false,
							gold: 0,
							score: 0
						})

						that.calculate();
					};
				};
			}
		})
	},
	//选择优惠券
	choosePromotion: function() { 
		wx.navigateTo({
			url: '/pages/coupons/index?canuse=true',
		})
	},
	//优惠券列表触发的选择事件
	usrpromotionFn(data) {
		var that = this;
		var promotionAmount= parseFloat(data.discountPrice);
		var totalAmount = that.data.orderInfo.buyerShouldPay-promotionAmount;
		var user_gold = that.data.user_gold;
		var user_integral = that.data.user_integral;

		var canUseGold = user_gold > totalAmount ? totalAmount : user_gold;
		var canUseScore = user_integral > totalAmount ? totalAmount : user_integral;

		that.setData({
			promotionAmount: promotionAmount,
			promotion: data,
			canUseGold: canUseGold,
			canUseScore: canUseScore,
			useGold: false,
			useScore: false,
			gold: 0,
			score: 0
		})

		this.calculate();
	},
	//获取订单详情
	getDetail: function(orderId) { 
		var that = this;
		var loginInfo = loginFn()
		loginInfo.orderId = orderId
		wx.request({
			url: urls.orderinfo,
			data: loginInfo,
			success: function(res) {
				console.log(res)
				if (res.data.code == '0') {
					var data = res.data.data;
					var totalAmount = parseFloat(data.buyerShouldPay)
					that.setData({
						orderInfo: res.data.data,
						totalAmount: Math.floor(totalAmount * 100) / 100,
						user_gold: data.leftGold,
						user_integral: data.leftScore,
						number: parseInt(res.data.data.goodsCount),
						canUseGold: data.leftGold > totalAmount ? totalAmount : data.leftGold,
						canUseScore: data.leftScore > totalAmount ? totalAmount : data.leftScore,
					})
					//优惠券
					//推荐优惠券
					that.getpromotion(totalAmount);

				};
			}
		})
	},
	usepromotion: function(promotionId) {
		var that = this;
		var loginInfo = loginFn()
		loginInfo.promotionId = promotionId
		wx.request({
			url: urls.promotion,
			data: loginInfo,
			success: function(res) {
				if (res.data.code == '0') {
					that.setData({
						promotion: res.data.data
					})
				};
			}
		})
	}
})
